package io.sdph.order;

import io.sdph.documents.model.Invoice;
import io.sdph.order.dao.OrderManagerDAO;
import io.sdph.order.exceptions.OrderException;
import io.sdph.order.model.Order;
import io.sdph.products.model.Product;
import io.sdph.userprofile.model.User;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * Manager zarządzający zamówieniami.
 * 
 * @author Adrian Szwajkowski, Tomasz Korpowski
 * @since 0.0.1
 */
@Service
public class OrderManager implements IOrderManager {

	@Autowired
	OrderManagerDAO orderManagerDAO;
	
	@Override
	public Order order(Map<Product, Long> products, Map<String, String> properties, Invoice invoice)
			throws OrderException 
	{
		Order order = orderManagerDAO.order(products, properties, invoice);
        
        if(order == null) throw new OrderException("Wystapil problem z dodawaniem zamowienia do bazy danych.");
        return order;
	}

	@Override
	public void cancelOrder(Order order) throws OrderException {
		  boolean hasError = orderManagerDAO.cancelOrder(order);
	      if(hasError) throw new OrderException("Wystapil problem z anulowaniem zamowienia.");
	}

	@Override
	public void cancelOrder(String orderId) throws OrderException {
		 boolean hasError = orderManagerDAO.cancelOrder(orderId);
	        if(hasError) throw new OrderException("Wystapil problem z anulowaniem zamowienia o ID: " + orderId + " .");
	}

	@Override
	public List<Order> getUserOrders(User user) throws OrderException {
		List<Order> orders = new ArrayList<Order>();
        orders = orderManagerDAO.getUserOrders(user);
        
        if( orders == null ) throw new OrderException("Wystapil problem z pobieraniem zamowien.");
        return orders;
	}
	
	@Override
	public List<Order> getUserOrderHistory(User user, Date dateFrom, Date dateTo) throws OrderException {
		List<Order> orders = new ArrayList<Order>();
		orders = orderManagerDAO.getUserOrderHistory(user, dateFrom, dateTo);
		
		if( orders == null ) throw new OrderException("Wystapil problem z pobieraniem historii zamowien uzytkownika.");
		return orders;
	}
	
	@Override
	public void fill(Order order) throws OrderException {
		orderManagerDAO.fill(order);
	}

	@Override
	public Order getOrder(String orderId) throws OrderException {
		Order order = orderManagerDAO.getOrder(orderId);
		
		if(order == null) throw new OrderException("Wystapil problem z pobieraniem zamowienia z bazy danych.");
        return order;
	}
}
